var functions = {
  /**
   * @name 判断传入地址的图片是否加载成功
   * @param {str} imgurl 
   * @param {function} callback 
   */
  imgLoad(imgurl, callback) {
    var img = new Image()
    img.src = imgurl
    if (callback) {
      callback()
    }
    return img.complete
  },

  /**
   * @name 倒计时
   * @param {int} time 
   * @param {function} callback
   */
  countDown(time, callback) {
    var timeDown = setInterval(() => {
      // return time
      if (time == 0) {
        clearInterval(timeDown)
        if (callback) callback()
      } else {
        time--
      }
    }, 1000)
  },

  /**
   * @name 获取当前路由path
   * @param {*} vue 
   */
  getRouterPath(vue) {
    var routerPath = vue.$router.history.current.path
    return routerPath
  },

  /**
   * @name 获取当前路由中携带的参数，返回param或者返回全部的参数
   * @param {*} vue 
   * @param {str} param 
   */
  getRouterParams(vue, param) {
    if (param) {
      return vue.$router.history.current.params.param
    } else {
      return vue.$router.history.current.params
    }
  },

  getBacImg(vue) {
    return 'background:url(' + localStorage.getItem("homepageImg") + ');background-position-x:' + vue.$store.state.homePageBac.positionX + ';background-position-y:' + vue.$store.state.homePageBac.positionY + ';background-size:' + vue.$store.state.homePageBac.bacSize
  },

  /**
   * @name 从array中获取符合的obj
   */
  getRightItem(array, key, value) {
    for (var item of array) {
      if (item[key] == value) {
        return item
      }
    }
  },

  
  /**
   * @name 信息提示窗口
   * @param {*} res 
   */
  toMessage(res = { error: 0, msg: "成功" }) {
    var result = {
      message: res.msg,
      duration: res.error == 2 ? 1500 : 2000
    }
    switch (res.error) {
      case 0: window._bus.$toast.success(result); break;
      case 1: window._bus.$toast.fail(result); break;
      case 2: window._bus.$toast(result); break;
    }
  },

  /**
   * @name 调用方法序列
   * @param {*} array 
   */
  async orderMethods(array = []) {
    for (var i = 0; i < array.length; i++) {
      await array[i]()
    }
  },

  /**
   * @name 检查参数
   * @param {*} model 数据模板
   * @param {*} params 检查的数据
   */
  checkParams(model, params) {
    if (!model) throw new Error('数据模板不能为空')
    if (!params) throw new Error('检查的数据不能为空')
    var result = false
    model.forEach(ele => {
      if (ele.checked && !params[ele.prop]) {
        _g.toMessage({ error: 1, msg: ele.label + "不能为空" })
        result = true
      }
    })
    return result
  },

  /**
   * @name apiPost 封装post方法
   * @param {*} url 
   * @param {*} data 
   * @param {*} canClose
   */
  async apiPost(url, data, isLoading,canClose) {
    var path = PATH + url
    var result = null
    var isLoading=isLoading===undefined?window.showLoading:isLoading
    var canClose = canClose===undefined
    if(isLoading)_g.showLoading()
    if (sessionStorage.getItem('number') && data) data.number = sessionStorage.getItem('number');

    try {
      await $axios.post(path, qs.stringify(data)).then(res => {
        if(canClose)_g.closeLoading()
        return result = res
      });
      
    }
    catch (err) {
      _g.closeLoading()
      var message = "出问题了"
      switch (err.toString().split(" ").slice(-1)[0]) {
        case "404": message = "访问地址不正确"; break;
        case "500": message = "后台出错"; break;
      }
      _g.toMessage({ type: "warning", msg: message })
    }
    return await result ? result.data : null;
  },

 /**
  * @name littleImg 压缩图片
  * @param {*} file 
  * @param {*} callback 回调函数
  */
  littleImg(file,callback) {
    var file = file
    //创建读取文件的对象
    var reader = new FileReader();
    //创建文件读取相关的变量
    var imgFile;

    //为文件读取成功设置事件
    reader.onload = function (e) {
      imgFile = e.target.result;
      var img = new Image()
      var canvas = document.createElement('canvas');
      var context = canvas.getContext('2d');
      img.src = imgFile

      img.onload = function () {
        // 图片原始尺寸
        var originWidth = this.width;
        var originHeight = this.height;
        // 最大尺寸限制
        var maxWidth = 500, maxHeight = 500;
        // 目标尺寸
        var targetWidth = originWidth
        var targetHeight = originHeight;
        // 图片尺寸超过400x400的限制
        if (originWidth > maxWidth || originHeight > maxHeight) {
          if (originWidth / originHeight > maxWidth / maxHeight) {
            // 更宽，按照宽度限定尺寸
            targetWidth = maxWidth;
            targetHeight = Math.round(maxWidth * (originHeight / originWidth));
          } else {
            targetHeight = maxHeight;
            targetWidth = Math.round(maxHeight * (originWidth / originHeight));
          }
        }
        // canvas对图片进行缩放
        canvas.width = targetWidth;
        canvas.height = targetHeight;
        // 清除画布
        context.clearRect(0, 0, targetWidth, targetHeight);

        // 处理手机拍照旋转的bug
        var orient = _g.getPhotoOrientation(img);
        // alert(orient)
        if (orient == 6) {
          context.save();//保存状态
          context.translate(targetWidth / 2, targetHeight / 2);//设置画布上的(0,0)位置，也就是旋转的中心点
          context.rotate(90 * Math.PI / 180);//把画布旋转90度
          // 执行Canvas的drawImage语句
          context.drawImage(img, - targetHeight / 2, - targetWidth / 2, targetHeight, targetWidth);//把图片绘制在画布translate之前的中心点，
          context.restore();//恢复状态
        } else {
          // 执行Canvas的drawImage语句
          context.drawImage(img, 0, 0, targetWidth, targetHeight);
        }

        // 图片压缩
        // context.drawImage(img, 0, 0, targetWidth, targetHeight);
        var final = canvas.toDataURL("image/jpeg")

        // alert(final)
        if(callback)callback(_g.dataURLtoFile(final))
      }
    };
    //正式读取文件
    reader.readAsDataURL(file);
  },

  // exif.js 中用来获取图片信息的
  getPhotoOrientation(img) {
    if(!EXIF)console.error("确认已经引入exif.js");
    
    var orient;
    EXIF.getData(img, function () {
      orient = EXIF.getTag(this, "Orientation");
    });
    return orient;
  },

  /**
   * @name dataURLtoFile 图片地址转存为file
   * @param {*} dataurl 
   * @param {*} filename 
   */
  dataURLtoFile(dataurl, filename = 'file') {
    let arr = dataurl.split(',')
    let mime = arr[0].match(/:(.*?);/)[1]
    let suffix = mime.split('/')[1]
    let bstr = atob(arr[1])
    let n = bstr.length
    let u8arr = new Uint8Array(n)
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n)
    }
    return new File([u8arr], `${filename}.${suffix}`, { type: mime })
  },

  /**
   * @name 显示加载中
   */
  showLoading(){
    window._bus.$toast.loading({
      duration: 0,
      mask: true,
      loadingType:"spinner",
      message: '用力加载中...'
    })
  },
  closeLoading(){
    window._bus.$toast.clear()
  },


  /**
   * @name 生成[num]的数组
   * @param {*} num 
   */
  getNumArray(num) {
    return new Array(num).fill("").map((val, index) => (index + 1))
  },

  // 全屏
  /**
   * @name 全屏显示局部元素
   * @param {*} id 
   * @param {*} vue 
   * @param {function} callback
   */
  fullScreen(id, vue, callback) {
    if (!id) throw new Error("全屏元素的id必填")

    let fullarea = document.getElementById(id);

    if (vue.isFullScreen) {
      // 退出全屏
      if (document.exitFullscreen) {
        document.exitFullscreen();
      } else if (document.webkitCancelFullScreen) {
        document.webkitCancelFullScreen();
      } else if (document.mozCancelFullScreen) {
        document.mozCancelFullScreen();
      } else if (document.msExitFullscreen) {
        document.msExitFullscreen();
      }
    } else {
      // 进入全屏
      if (fullarea.requestFullscreen) {
        fullarea.requestFullscreen();
      } else if (fullarea.webkitRequestFullScreen) {
        fullarea.webkitRequestFullScreen();
      } else if (fullarea.mozRequestFullScreen) {
        fullarea.mozRequestFullScreen();
      } else if (fullarea.msRequestFullscreen) {
        // IE11
        fullarea.msRequestFullscreen();
      }
    }

    if (callback) {
      setTimeout(() => {
        callback()
      }, 200)
    }

    vue.$set(vue, 'isFullScreen', !vue.isFullScreen)
  },

  /**
   * @name 单个数字转换为大写
   * @param {*} word 
   */
  toUp(word) {
    switch (word) {
      case "0": return "零"
      case "1": return "壹"
      case "2": return "贰"
      case "3": return "叁"
      case "4": return "肆"
      case "5": return "伍"
      case "6": return "陆"
      case "7": return "柒"
      case "8": return "捌"
      case "9": return "玖"
    }
  },

  /**
   * @name 格式化时间
   * @param {*} time 
   * @param {*} type 
   */
  formatTime(time,type){
    switch(type){
      case "date": return new Date(time).getFullYear()+'-'+(new Date(time).getMonth()+1)+'-'+new Date(time).getDate();
      case "time": return time
      case "datetime": return new Date(time).getFullYear()+'-'+(new Date(time).getMonth()+1)+'-'+new Date(time).getDate() +" "+new Date(time).getHours()+":"+new Date(time).getMinutes();
    }
  },


  /**
   * @name a标签特性
   * @param {*} tel 
   */
  telTo(tel){
    location.href=`tel:${tel}`
  },
  emailTo(email){
    location.href=`emailTo:${email}`
  },

  /**
   * @name 拓展方法
   * @param {*} name 
   * @param {*} method 
   */
  fn(name, method) {
    if (!method) throw new Error("拓展方法未定义")
    if (Object.keys(this).includes(name)) throw new Error("方法名" + name + "重复")
    this[name] = method
  }

}

export default functions